<!DOCTYPE html>
<html lang="cn">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Layui-Tinymce</title>
    <link rel="stylesheet" href="../layui/css/layui.css">
    <link rel="stylesheet" href="../css/cropper.min.css">
    <style>
        body {
            padding: 20px 20px;
            background-color: #f2f3f5;
        }

        .cover-box {
            display: flex;
        }

        /* 左侧裁剪区域 */
        .cover-left {
            width: 400px;
            height: 280px;
            overflow: hidden;
            margin-right: 20px;
        }

        .cover-right {
            display: flex;
            flex-direction: column;
            align-items: center;
        }

        /* 预览区域 */
        .img-preview {
            width: 200px;
            height: 140px;
            background-color: #ccc;
            overflow: hidden;
            margin-bottom: 20px;
        }
    </style>
</head>


<body>
    <div class="layui-card">
        <div class="layui-card-header">
            写文章
        </div>
        <div class="layui-card-body">
            <!-- 发布文章的表单 -->
            <form class="layui-form" id="form-pub" enctype="multipart/form-data">
                <!-- 文章标题 -->
                <div class="layui-form-item">
                    <label class="layui-form-label">文章标题</label>
                    <div class="layui-input-block">
                        <input type="text" name="title" required lay-verify="required" placeholder="请输入标题"
                            autocomplete="off" class="layui-input">
                    </div>
                </div>
                <!-- 文章类别 -->
                <div class="layui-form-item">
                    <label class="layui-form-label">文章分类</label>
                    <div class="layui-input-block">
                        <select name="cate_id" lay-verify="required" id="cateId">

                        </select>
                    </div>
                </div>
                <!-- 文章内容 -->
                <div class="layui-form-item">
                    <label class="layui-form-label">文章内容</label>
                    <div class="layui-input-block">
                        <div>
                            <!-- <div class="layui-btn-group" style="margin-top: 10px">
                                <button class="layui-btn" lay-event="setByAjax">Ajax加载数据</button>
                                <button class="layui-btn" lay-event="setContent">设置内容</button>
                                <button class="layui-btn" lay-event="insertContent">插入内容</button>
                                <button class="layui-btn" lay-event="getContent">获取内容</button>
                                <button class="layui-btn" lay-event="getText">获取文本</button>
                                <button class="layui-btn" lay-event="clearContent">清空内容</button>
                            </div>
                            <hr /> -->
                            <textarea name="content"
                                id="edit">这里是<span style="color: #e03e2d;"><em>edit初始化</em></span>的内容</textarea>
                        </div>
                    </div>
                </div>
                <!-- 文章封面 -->
                <div class="layui-form-item">
                    <label class="layui-form-label">文章封面</label>
                    <!--  选择封面区域-->
                    <div class="layui-input-block cover-box">
                        <!-- 左侧裁剪区域 -->
                        <div class="cover-left">
                            <img src="../images/18.jpeg" alt="" width="100%" id="image">
                        </div>
                        <!-- 右侧裁剪后显示的图片 -->
                        <div class="cover-right">
                            <!-- 预览区域 -->
                            <div class="img-preview"></div>
                            <button class="layui-btn layui-btn-danger" id="btnChooseImage">选择封面</button>
                            <!--  -->
                            <input type="file" id="coverFile" style="display: none;"
                                accept="image/png,image/jpeg,image/jpg,image/gif" name="cover_img">
                        </div>
                    </div>
                </div>
                <!-- 发布 -->
                <div class="layui-form-item">
                    <div class="layui-input-block">
                        <button type="submit" class="layui-btn" lay-submit lay-event="getContent">发布</button>
                    </div>
                </div>
            </form>


        </div>
        <!-- card body end -->
    </div>
    <script type="text/html" id="tpl-cate">
        <option value="">请选择文章分类</option>
        {{each data}}
        <option value="{{$value.id}}">{{$value.name}}</option>
        {{/each}}
    </script>

</body>

</html>
<script src="../js/jquery-3.6.1.min.js"></script>
<script src="../layui/layui.js"></script>
<script src="../js/cropper.min.js"></script>
<script src="../js/template-web.js"></script>
<script>
    var fwb = null;
    /^http(s*):\/\//.test(location.href) || alert('请先部署到 localhost 下再访问');
    layui.extend({
        tinymce: '{/}../layui_exts/tinymce/tinymce'
    }).use(['tinymce', 'util', 'layer'], function () {
        var t = layui.tinymce
            , util = layui.util
            , layer = layui.layer
            , $ = layui.$

        var edit = t.render({
            elem: "#edit"
            , height: 200
            // ...
            // 其余配置可参考官方文档
        }, function (opt, edit) {
            //加载完成后回调
        });

        t.render({
            elem: "#edit2"
            , height: 200
            , init_instance_callback: function (ed) {
                ed.on('KeyPress', function (e) {

                });
            }

        });

        util.event('lay-event', {
            setByAjax: function () {
                $.ajax({
                    url: '../layui_exts/mock/content.json',
                    success: function (res) {
                        t.get('#edit').setContent(res.data.content)
                    }
                })
            },
            //获取富文本的内容
            getContent: function () {
                var content = t.get('#edit').getContent()
                fwb = content;
            },

        });

    });

    // 点击了选择封面
    var imgs = $('#image');
    var options = {
        aspectRatio: 400 / 280,
        preview: '.img-preview'
    }

    imgs.cropper(options);

    $('#btnChooseImage').on('click', function (e) {
        e.preventDefault();
        //模拟点击
        $('#coverFile').click();
    })
    //监听change事件
    $('#coverFile').on('change', function (e) {
        var files = e.target.files;
        if (files.length == 0) return;
        var newImgURL = URL.createObjectURL(files[0]);
        //
        imgs.cropper('destroy').attr('src', newImgURL).cropper(options);

    })
    //获取分类
    $.ajax({
        type: 'get',
        url: '/my/article/cates',
        headers: {
            'Authorization': localStorage.getItem('token')
        },
        success: (res) => {

            var htmlStr = template('tpl-cate', res);


            $('#cateId').html(htmlStr);
            // 重新渲染form
            layui.form.render();
        }
    })


    //
    $('#form-pub').on('submit', function (e) {
        e.preventDefault();
        let frData = new FormData($(this)[0]);
        frData.append('state', '已发布');
        //创建需要上传的封面图片
        imgs.cropper('getCroppedCanvas', {
            //创建一个Canvas画布
            width: 400,
            height: 280,
        }).toBlob(function (blob) {
            //将canvas画布上的内容，转换为文件对象
            //
            console.log(blob);
            frData.append('cover_img', blob);
        });
        //发起一个发布文章的ajax请求
        $.ajax({
            type: 'post',
            headers: {
                'Authorization': localStorage.getItem('token')
            },
            url: '/my/article/add',
            processData: false,//告诉jquery不要去处理请求的数据格式
            contentType: false,//告诉jquery不要设置请求头的类型
            data: frData,
            success: (res) => {
                layer.msg(res.message);
            }
        })
    })
</script>